package com.seemovies.sdk.retrofit;

import android.util.Log;

import com.google.gson.GsonBuilder;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Converter;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 * Created by Jarchie on 2017\11\7.
 * 描述：基础Api的实现类
 */

@SuppressWarnings({"NullableProblems", "WeakerAccess"})
public class BaseApiImpl implements BaseApi {
    private volatile static Retrofit mRetrofit = null;
    protected Retrofit.Builder mRetrofitBuilder = new Retrofit.Builder();
    protected OkHttpClient.Builder mClientBuilder = new OkHttpClient.Builder();

    public BaseApiImpl(String baseUrl) {
        mRetrofitBuilder.addConverterFactory(ScalarsConverterFactory.create())
                //添加Gson转换器
                .addConverterFactory(GsonConverterFactory.create(new GsonBuilder().setLenient().create()))
                //添加Retrofit到RxJava的转换器
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(mClientBuilder.addInterceptor(getLoggerInterceptor()).build())
                .baseUrl(baseUrl);
    }

    /**
     * 构建Retrofit
     *
     * @return Retrofit对象
     */
    @Override
    public Retrofit getRetrofit() {
        if (mRetrofit == null) {
            synchronized (BaseApiImpl.class) {
                if (mRetrofit == null) {
                    mRetrofit = mRetrofitBuilder.build(); //创建Retrofit对象
                }
            }
        }
        return mRetrofit;
    }

    @Override
    public OkHttpClient.Builder setInterceptor(Interceptor interceptor) {
        return mClientBuilder.addInterceptor(interceptor);
    }

    @Override
    public Retrofit.Builder setConverterFactory(Converter.Factory factory) {
        return mRetrofitBuilder.addConverterFactory(factory);
    }

    /**
     * 日志拦截器，访问的接口信息
     *
     * @return 拦截器
     */
    public HttpLoggingInterceptor getLoggerInterceptor() {
        //日志显示级别
        HttpLoggingInterceptor.Level level = HttpLoggingInterceptor.Level.HEADERS;
        //新建log拦截器
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                Log.e("ApiUrl------>", message);
            }
        });
        loggingInterceptor.setLevel(level);
        return loggingInterceptor;
    }

}
